package com.future.direction.jpush;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;

import com.future.direction.R;
import com.future.direction.common.Constant;
import com.future.direction.common.util.ACache;
import com.future.direction.common.util.JsonUtils;
import com.future.direction.common.util.LogUtil;
import com.future.direction.common.util.StringUtil;
import com.future.direction.common.util.UIUtil;
import com.future.direction.ui.activity.MainActivity;

import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;

import static android.content.Context.NOTIFICATION_SERVICE;

/**
 * 自定义接收器
 * 如果不定义这个 Receiver，则： 1) 默认用户会打开主界面 2) 接收不到自定义消息
 */
public class JpushReceiver extends BroadcastReceiver {
    private Context mContext;
    private static final String TAG = "JIGUANG";
    public static String regId;

    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        Bundle bundle = intent.getExtras();
        String msg = bundle.getString(JPushInterface.EXTRA_EXTRA);
        try {
            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
                regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                LogUtil.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
                //send the Registration Id to your server...

            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                LogUtil.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息(内容为): " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
                // 自定义消息不是通知，默认不会被SDK展示到通知栏上，极光推送仅负责透传给SDK。其内容和展示形式完全由开发者自己定义。
                // 自定义消息主要用于应用的内部业务逻辑和特殊展示需求
            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
                LogUtil.d(TAG, "[MyReceiver] 接收到推送下来的通知");

                String extra_json = bundle.getString(JPushInterface.EXTRA_EXTRA);
                LogUtil.d(TAG, "[MyReceiver] 接收到推送下来的通知附加字段" + extra_json);

                // 可以利用附加字段来区别Notication,指定不同的动作,extra_json是个json字符串
                // 通知（Notification），指在手机的通知栏（状态栏）上会显示的一条通知信息
            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                LogUtil.d(TAG, "[MyReceiver] 用户点击打开了通知");
                LogUtil.d(TAG, "[MyReceiver] 用户点击打开了通知" + bundle.getString(JPushInterface.EXTRA_EXTRA));
                // 在这里根据 JPushInterface.EXTRA_EXTRA(附加字段) 的内容处理代码，
                // 比如打开新的Activity， 打开一个网页等..
                jump(bundle.getString(JPushInterface.EXTRA_EXTRA));
            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                LogUtil.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                LogUtil.w(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
            } else {
                LogUtil.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
		/*MessageReceiveBean messageReceiveEntity =null;
		if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {

		} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
			//接收到消息
			messageReceiveEntity = parseMsgData(msg);
//			if(null != messageReceiveEntity) {
//				notificationUtil.sendNotification();
//			}
//			notificationUtil.sendNotification();
		} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
			//打开消息处理
			messageReceiveEntity = parseMsgData(msg);
			jump(messageReceiveEntity);
		} else if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
			//保存registrationId
			JpushUtil.saveRegistionId();
		}*/
    }


    private MessageReceiveBean parseMsgData(String msg) {
        MessageReceiveBean messageReceiveEntity = null;
        if (msg != null && !msg.equals("")) {
            try {
                JSONObject json = new JSONObject(msg);
                String data = json.getString("data");
                messageReceiveEntity = JsonUtils.fromJson(data, MessageReceiveBean.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return messageReceiveEntity;
    }


    /**
     * 消息跳转
     */
    private void jump(String extra_json) {
        try {
            if (extra_json.contains("assetCode")) {

            }
        } catch (Exception e) {
        }
    }

    private void processCustomMessage(Context context, Bundle bundle) {

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder notification = new NotificationCompat.Builder(context);

        notification.setAutoCancel(true)
                .setContentText("自定义推送声音")
                .setContentTitle("测试")
                .setSmallIcon(R.mipmap.ic_launcher);

        /*String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        if (!TextUtils.isEmpty(extras)) {
            try {
                JSONObject extraJson = new JSONObject(extras);
                if (null != extraJson && extraJson.length() > 0) {


                    String sound = extraJson.getString("sound");

                    if ("".equals(sound)) {
                        notification.setSound(Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.out_need));
                    }

                }
            } catch (JSONException e) {

            }

        }*/
        Intent mIntent = new Intent(context, MainActivity.class);

        mIntent.putExtras(bundle);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, mIntent, 0);

        notification.setContentIntent(pendingIntent);

        notificationManager.notify(2, notification.build());

    }

}
